# 蓝思粘贴文字

import json
import os
import sys
import tkinter as tk
from tkinter import filedialog
import time

import keyboard
import pyautogui
# import pyperclip

def ms_to_seconds(ms):
    return ms / 1000.0

def load_config(file_path):
    with open(file_path, 'r',encoding='utf-8') as f:
        return json.load(f)

def auto_click_sequence(config):
    click_selection = config['click_selection']
    click_sequence = config['click_sequence']

    try:
        print(f"程序将在2000毫秒后开始执行...")
        time.sleep(ms_to_seconds(2000))

        # 2，点击选择框位置
        print(f"点击选择框位置")
        for i in range(0, len(click_selection)):
            pos = click_selection[i]['position']
            wait = click_selection[i]['wait_time']
            pyautogui.moveTo(pos[0], pos[1], duration=0.5)
            pyautogui.click()
            time.sleep(ms_to_seconds(wait))

        # 1，点击第一个位置
        print(f"粘贴文字")
        for j in range(0, len(click_sequence)):
            pos = click_sequence[j]['position']
            text= click_sequence[j]['text']
            pyautogui.moveTo(pos[0], pos[1], duration=0.5)
            pyautogui.click()
            keyboard.write(text, delay=0.05)


        # # 在第一个位置的文本框中输入 "被点击"
        # if j == 1:
        #     # 方法1：使用 pyperclip将文字复制到剪贴板，模拟粘贴操作
        #     # pyperclip.copy("被点击")  # 将文字复制到剪贴板
        #     # time.sleep(0.2)
        #     # pyautogui.hotkey("ctrl", "v")  # 模拟粘贴操作
        #
        #     # 方法2：使用 keyboard直接输入文字
        #     keyboard.write("被点击",delay=0.05)

        print("\n所有点击序列执行完成！")

    except pyautogui.FailSafeException:
        print("触发了故障保护，程序已停止")

# 定义一个监听键盘事件的函数
# 监听 Ctrl+Z 并退出程序的函数
def listen_for_ctrl_z(stop_event):
    print("按Ctrl+Z退出程序...")
    while True:
        if keyboard.is_pressed('ctrl+z'):  # 检测是否按下Ctrl+Z
            print("检测到Ctrl+Z，程序正在退出...")
            stop_event.set()  # 设置事件，通知主线程停止
            sys.exit(0)

if __name__ == "__main__":
    i = input("输入1开始自动点击，输入其他数字退出：")
    if i == '1':
        try:
            # 创建一个隐藏的 Tkinter 主窗口
            root = tk.Tk()
            root.withdraw()

            # 弹出文件选择框
            file_path = filedialog.askopenfilename(
                title="请选择配置文件",
                filetypes=[("JSON文件", "*.json"), ("所有文件", "*.*")]
            )

            if not file_path:
                print("未选择文件，程序退出。")
                exit()

            # 加载配置并执行逻辑
            config = load_config(file_path)
            auto_click_sequence(config)
        except Exception as e:
            print(f"程序执行失败: {str(e)}")
    else:
        exit()


